<template>
  <main class="v-slot-table">
    <div
      v-for="model in slotData"
      :key="model.id"
      class="g-relative _table_group"
    >
      <div class="g-flex _table-row g-ov-hidden _table-title">
        <div
          class="g-flex-0 _name-column g-one-line"
          style="height: 24px"
        >
          {{ model.name }}
        </div>
      </div>
      <div
        class="v-collapse"
        @click="handleCollapse(model.id)"
      >
        <img
          v-if="hiddenIds.has(model.id)"
          src="statics/icons/app/treeiconshrink.svg"
          alt=""
        />
        <img
          v-else
          src="statics/icons/app/treeiconspread.svg"
          alt=""
        />
      </div>
      <div
        v-for="row in getRows(model)"
        :key="row.slotId"
        class="g-flex _table-row g-ov-hidden"
        style="background: #fff"
        :class="{ '_current-row': row.id_ === activeRowId }"
        @click="handleClickRow(row)"
      >
        <div
          v-show="row.id_ === activeRowId"
          class="_table-body-icon"
        >
          <img src="statics/icons/app/arrowchoose.svg" />
        </div>
        <div
          class="g-flex-0 _cell _name-column g-one-line"
          :style="{ width: nameColumnWidth + 'px' }"
        >
          {{ row.name }}
        </div>
        <div class="g-flex g-flex-1 _cell _value-column">
          <div class="g-flex-1">
            <div
              v-for="item in row.values"
              :key="item.id"
              :class="{ '_active-row': item.id === activeSlotValueId }"
              @click="activeSlotValueId = item.id"
            >
              <component
                :is="propertyManager.getSlotPropertyEditor(row)"
                :instanceId="modelId"
                :projectId="projectId"
                :slotData="row"
                :slotValue="item"
                :slotKey="SlotEditKey.SlotValue"
                :readonly="isModelDisabled"
                :isMultiplicity="row.isMultiplicity"
                :nullable="row.nullable"
                :selected="item.id === activeSlotValueId"
                :row="item"
                @delete-slot-value="deleteSlotValue(row)"
              />
            </div>
          </div>
          <div
            v-show="row.id_ === activeRowId && !row.hidden && !isModelDisabled"
            class="g-flex-0 _editor-height"
            :class="{ '_string-editor': row.dataType && row.dataType === PropertyDataType.STRING }"
          >
            <div
              class="g-m-l-5"
              style="height: 12px"
            >
              <img
                src="statics/icons/app/iconadd.png"
                class="g-pointer"
                @click="slotsPaneModel.addSlotValue(row)"
              />
            </div>
            <div
              class="g-m-t-4 g-m-l-5"
              style="height: 12px"
            >
              <img
                src="statics/icons/app/iconreduce.png"
                class="g-pointer"
                :class="{ _disabled: !activeSlotValueId }"
                @click="deleteSlotValue(row)"
              />
            </div>
            <div
              v-show="row.dataType && row.dataType === PropertyDataType.STRING && !row.hidden && !isModelDisabled"
              class="g-m-t-4 g-m-l-5 g-pointer"
              style="height: 12px"
            >
              <img
                src="statics/icons/app/iconmodify.svg"
                class="g-pointer"
                :class="{ _disabled: !activeSlotValueId }"
                @click="editSlotValue(row, model.id)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>
<script lang="ts" setup>
import { SlotsInPropertyPane } from "@/modules/model/service/archServiceDto";
import { ref, inject, Ref } from "vue";
import { InstanceSlotData } from "./types";
import { propertyManager } from "./PropertyManager";
import { SlotEditKey } from "@/constants/constants";
import { SlotsPaneModel } from "./models/SlotsPaneModel";
import { propertyUtil } from "./PropertyUtil";
import TextEditor from "@/modules/model/comps/station/sider/attribute/propertyEditors/modals/TextEditor.vue";
import { BusEvent, PropertyDataType } from "@/constants/Enums";

const props = defineProps<{
  slotData: SlotsInPropertyPane[];
  modelId: string;
  projectId: string;
  nameColumnWidth: number;
  slotsPaneModel: SlotsPaneModel;
  activeRowId?: number;
}>();

const emit = defineEmits<{
  (e: "handleClickRow", row: any, index: number): void;
}>();

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;
const activeSlotValueId = ref("");
const hiddenIds = ref(new Set<string>());

const getRows = (data: SlotsInPropertyPane) => {
  if (hiddenIds.value.has(data.id)) {
    return [];
  } else {
    return data.children;
  }
};

const handleCollapse = (id: string) => {
  if (hiddenIds.value.has(id)) {
    hiddenIds.value.delete(id);
  } else {
    hiddenIds.value.add(id);
  }
};

const deleteSlotValue = async (row: InstanceSlotData) => {
  const slotValue = row.values.find(item => item.id === activeSlotValueId.value);
  if (!slotValue) return;
  await propertyUtil.deleteSpecification({
    projectId: props.projectId,
    specificationId: slotValue.id,
    slotId: row.slotId!
  });
  activeSlotValueId.value = "";
};

const editSlotValue = async (row: InstanceSlotData, parentId: string) => {
  const slotValue = row.values.find(item => item.id === activeSlotValueId.value);
  if (!slotValue) return;
  const newText = await TextEditor.popup({
    title: row.name,
    text: slotValue.value
  });

  const res = await propertyUtil.updatePropertySlotAndFresh({
    projectId: props.projectId,
    propertyId: row.propertyId!,
    slotId: row.slotId,
    parentId,
    value: newText || "",
    valueSpecificationId: slotValue.id
  });

  if (res) {
    app.$bus.emit(BusEvent.REFRESH_SLOT, parentId);
  }
};

const handleClickRow = (row: InstanceSlotData) => {
  if (row.slotId) {
    if (props.activeRowId !== row.id_) {
      let slotValue = row.values.find(item => item.id === activeSlotValueId.value);
      if (!slotValue) {
        slotValue = row.values[0];
        slotValue && (activeSlotValueId.value = slotValue.id);
      }
    }
    emit("handleClickRow", { key: row.slotId }, 0);
  }
};
</script>
<style lang="scss">
@import "@/assets/css/theme.scss";
.v-slot-table {
  ._table_group {
    border-bottom: 0 !important;
  }
  ._active-row {
    background-color: $nth-of-type-bg-color !important;
  }
  ._disabled {
    cursor: not-allowed;
  }
  ._editor-height {
    min-height: 48px;
    width: 30px;
    border-left: 1px solid rgb(221, 221, 221);
  }
  ._string-editor {
    min-height: 72px;
  }
}
</style>
